package info.batcloud.fanli.background.task.scheduler;

import info.batcloud.fanli.core.service.JdUnionService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.JdUnionContextSetting;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.Calendar;
import java.util.Date;

@Component
public class JdUnionScheduler {

    @Inject
    private JdUnionService jdUnionService;

    @Inject
    private SystemSettingService systemSettingService;

    @PostConstruct
    public void init() {
        jdUnionService.refreshAccessToken();
    }

    //每隔2小时刷新一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void refreshToken() {
        jdUnionService.refreshAccessToken();
    }

    @Scheduled(cron = "${cron.jdUnion.orderFetch}")
    public void fetchOrder() {
        JdUnionContextSetting contextSetting = systemSettingService.findActiveSetting(JdUnionContextSetting.class);
        Date now = new Date();
        Date startTime, endTime;
        if (contextSetting.getLastOrderFetchEndTime() == null) {
            //如果最后时间为0，那么从当前开始前7天的时间
            startTime = DateUtils.truncate(DateUtils.addDays(now, -7), Calendar.DATE);
            endTime = now;
        } else {
            startTime = contextSetting.getLastOrderFetchEndTime();
            endTime = now;
        }
        //如果时间差小于2小时，那么则从2小时开始
        if(endTime.getTime() - startTime.getTime() <= 60 * 60 * 2 * 1000 ) {
            startTime = DateUtils.addHours(endTime, -2);
        }

        while (true) {
            String time;
            if (!DateUtils.isSameDay(startTime, endTime)) {
                time = DateFormatUtils.format(startTime, "yyyyMMdd");
                startTime = DateUtils.addDays(startTime, 1);
            } else {
                if(startTime.after(now)) {
                    startTime = now;
                }
                time = DateFormatUtils.format(startTime, "yyyyMMddHH");
                startTime = DateUtils.addHours(startTime, 1);
            }
            jdUnionService.fetchOrder(time);
            if (startTime.after(endTime)) {
                break;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        contextSetting.setLastOrderFetchEndTime(startTime);
        systemSettingService.saveSetting(contextSetting, 0);
        systemSettingService.activeSetting(JdUnionContextSetting.class, 0);
    }
}
